package com.google.product.controller;


import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author name
 * @since 2021-05-03
 */
@RestController
public class ProductTestController {

    @Autowired
    protected HttpServletRequest request;

    /*
    测试断路器
    如果10秒内，20个请求中异常率到50%，就熔断10秒钟，10秒后进来的第一个请求如果还是异常就再断开10秒，如果没有异常断路器就关闭。
     */
    //fallbackMethod：降级
    //commandProperties：配置断路器，不写就是默认值
    @GetMapping("/test/{id}")
    @HystrixCommand(fallbackMethod = "testFallBack", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "20"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000")
    })
    String test(@PathVariable("id") Integer id) throws InterruptedException {
        if (id == 1) {
//            Thread.sleep(200000);//测试yml的超时配置

        } else {
            throw new RuntimeException("");
        }

//        int i = 1/0;
//        System.out.println("product被访问");
        return "product-response";
    }

    // test的降级方法  方法的描述要和接口一致
    public String testFallBack(Integer id) {
        return "降级的返回";
    }

    @GetMapping("/t2")
//    @HystrixCommand(fallbackMethod = "t2FallBack")
    String t2(Integer id) {
        if (id == 1) {

            int i = 1 / 0;


        }
        return "t2ok";
    }

    public String t2FallBack(Integer id) {
        return "t2的降级方法";
    }

    @GetMapping("t3")
    String t3() {
        return request.getLocalAddr() + ":" + request.getLocalPort();
    }

}

